package com.pro01.backend.service;

import com.pro01.backend.mapper.*;
import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.PointLog;
import com.pro01.backend.pojo.ShopItem;
import com.pro01.backend.pojo.ShopOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ShopItemService {

    @Autowired
    private ShopItemMapper shopItemMapper;

    @Autowired
    private UserPointMapper userPointMapper;

    @Autowired
    private PointLogMapper pointLogMapper;

    @Autowired
    private ShopOrderMapper shopOrderMapper;

    @Autowired
    private UserInviteService userInviteService;

    @Autowired
    private UserMapper userMapper;

    // 用户查看商品列表
    public PageResult<ShopItem> getActiveItems(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<ShopItem> records = shopItemMapper.getActiveItemsPaged(offset, pageSize);
        int total = shopItemMapper.countActiveItems();
        return new PageResult<>(total, records);
    }

    // 用户兑换商品
    public void redeemItem(Long userId, Long itemId) {
        ShopItem item = shopItemMapper.getById(itemId);
        if (item == null || !"ACTIVE".equals(item.getStatus())) {
            throw new RuntimeException("商品不存在或已下架");
        }

        Integer userPoints = userPointMapper.getUserPoints(userId);
        if (userPoints == null || userPoints < item.getPointsRequired()) {
            throw new RuntimeException("积分不足，无法兑换");
        }

        // 1. 扣积分
        userPointMapper.subtractPoints(userId, item.getPointsRequired());

        // 2. 写积分日志
        PointLog log = new PointLog();
        log.setUserId(userId);
        log.setPoints(item.getPointsRequired());
        log.setChangeType("EXPENSE");
        log.setSource("REDEEM");
        log.setDescription("兑换商品：" + item.getName());
        pointLogMapper.insertPointLog(log);

        // 3. 准备订单记录
        ShopOrder order = new ShopOrder();
        order.setUserId(userId);
        order.setItemId(item.getId());
        order.setItemName(item.getName());
        order.setPointsSpent(item.getPointsRequired());

        // 根据商品类型处理兑换结果（示例，仅处理邀请码，其他后续扩展）
        if ("INVITE_CODE".equals(item.getType())) {
            // 调用邀请码服务生成邀请码
            String inviteCode = userInviteService.generateInvite(userId);
            order.setStatus("COMPLETED");
            order.setResultInfo("邀请码：" + inviteCode);

        } else if ("USER_TITLE".equals(item.getType())) {
            // 设置用户称号
            if (item.getExtraValue() == null || item.getExtraValue().isBlank()) {
                throw new RuntimeException("商品未配置称号内容，无法兑换");
            }

            userMapper.updateUserTitle(userId, item.getExtraValue());

            order.setStatus("COMPLETED");
            order.setResultInfo("称号设置成功：" + item.getExtraValue());

        } else if ("NICKNAME_STYLE".equals(item.getType())) {
            if (item.getExtraValue() == null || item.getExtraValue().isBlank()) {
                throw new RuntimeException("商品未配置颜色样式，无法兑换");
            }

            userMapper.updateNicknameColor(userId, item.getExtraValue());

            order.setStatus("COMPLETED");
            order.setResultInfo("昵称颜色设置成功：" + item.getExtraValue());
        } else if ("AVATAR_FRAME".equals(item.getType())) {
            if (item.getExtraValue() == null || item.getExtraValue().isBlank()) {
                throw new RuntimeException("商品未配置头像框代号，无法兑换");
            }

            userMapper.updateAvatarFrame(userId, item.getExtraValue());

            order.setStatus("COMPLETED");
            order.setResultInfo("头像框设置成功：" + item.getExtraValue());
        } else if ("ADMIN_APPLICATION".equals(item.getType())) {
            order.setStatus("PENDING");
            order.setResultInfo("管理员申请待审核");

        } else {
            order.setStatus("COMPLETED");
            order.setResultInfo("兑换成功");
        }


        // 4. 插入订单
        shopOrderMapper.insertOrder(order);
    }

    // 用户查看兑换记录
    public PageResult<ShopOrder> getUserOrders(Long userId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<ShopOrder> records = shopOrderMapper.getOrdersByUser(userId, offset, pageSize);
        int total = shopOrderMapper.countOrdersByUser(userId);
        return new PageResult<>(total, records);
    }


    /**
     * 接下来是管理员接口
     */
    // 管理员添加商品
    public void addItem(ShopItem item) {
        int result = shopItemMapper.insertItem(item);
        if (result == 0) {
            throw new RuntimeException("商品添加失败");
        }
    }

    // 管理员下架商品
    public void disableItem(Long itemId) {
        int result = shopItemMapper.disableItem(itemId);
        if (result == 0) {
            throw new RuntimeException("下架失败，商品不存在或已下架");
        }
    }

    // 管理员重新上架商品
    public void enableItem(Long itemId) {
        int result = shopItemMapper.enableItem(itemId);
        if (result == 0) {
            throw new RuntimeException("上架失败，商品不存在或已上架");
        }
    }

    // 管理员分页查看所有商品
    public PageResult<ShopItem> getAllItems(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<ShopItem> records = shopItemMapper.getAllItemsPaged(offset, pageSize);
        int total = shopItemMapper.countAllItems();
        return new PageResult<>(total, records);
    }

    // 管理员审核晋升需求
    public void reviewAdminApplication(Long orderId, boolean approve, String reply) {
        ShopOrder order = shopOrderMapper.getOrderById(orderId);
        if (order == null || !"PENDING".equals(order.getStatus())) {
            throw new RuntimeException("订单不存在或不处于待审核状态");
        }

        if (approve) {
            // ✅ 设置用户为管理员
            userMapper.promoteToAdmin(order.getUserId());

            // ✅ 更新订单状态为 APPROVED
            shopOrderMapper.updateOrderStatus(orderId, "APPROVED", reply != null ? reply : "已通过审核");
        } else {
            // ✅ 拒绝
            shopOrderMapper.updateOrderStatus(orderId, "REJECTED", reply != null ? reply : "未通过审核");
        }
    }

    // 管理员查看兑换记录
    public PageResult<Map<String, Object>> getAllOrders(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<Map<String, Object>> records = shopOrderMapper.getAllOrdersPaged(offset, pageSize);
        int total = shopOrderMapper.countAllOrders();
        return new PageResult<>(total, records);
    }

}

